const app = getApp();
const config = require('../../config.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    startDate: '',
    endDate: '',
    winHeight: "",
    storage: '',
    pageCount: 10,
    index: 1,
    city: ['全部', '未受理', '已受理'],
    circleH: false,
    spread: false,
    //窗口高度    
    currentTab: 0,
    //预设当前项的值  
    scrollLeft: 0,
    //tab标题的滚动条位置  
    showViewTotal: false,
    showView: true,
    userInfo: null,
    loginUser: null,
    isFromSearch: true,
    // 用于判断searchSongList数组是不是空数组，默认true，空的数组    searchPageNum: 1, // 设置加载的第几次，默认是第一次      
    callbackcount: 10,
    //返回数据的个数    
    searchLoading: false,
    //"上拉加载"的变量，默认false，隐藏    
    searchLoadingComplete: false
    //“没有数据”的变量，默认false，隐藏   
  },

  swichNav: function (e) {
    var cur = e.target.dataset.current; 
    // console.info(cur); 
    // console.info(this.data.currentTab);
    if (this.data.currentTab == cur) {
      return false; 
    } else {
      this.setData({
        currentTab: cur,
        showView: false
      })
    }







  },
  formReset: function () {
    // console.log('form发生了reset事件')
  },
  bindPickerChange: function (e) {
    let sc = { "tab_wqs": "nav_1_1", "tab_yqs": "nav_1_1" }
    if (e.detail.value == 1) {
      sc = { "tab_wqs": "nav_1_1_h", "tab_yqs": "nav_1_1" };
    }
    if (e.detail.value == 2) {
      sc = { "tab_wqs": "nav_1_1", "tab_yqs": "nav_1_1_h" };
    }
    sc.index = e.detail.value;
    this.data.index = e.detail.value;
    this.setData(sc);
    //原查询方法使用与公办
    //getList(this);

    getOrderList(this);
  },
  weiqian: function (e) {
    this.setData({ "tab_wqs": "nav_1_1_h", "tab_yqs": "nav_1_1" });
    this.data.index = 1;
    //原查询方法使用与公办
    //getList(this);

    getOrderList(this);
  },
  yiqian: function (e) {
    this.setData({ "tab_wqs": "nav_1_1", "tab_yqs": "nav_1_1_h" });
    this.data.index = 2;
    //原查询方法使用与公办
    //getList(this);

    getOrderList(this);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.loginUser == null || app.loginUser.id == null && app.loginUser.mobile == null) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return;
    }
    // console.log(this.data.index);
    // console.log(getDate());

    this.setData({ "tab_wqs": "nav_1_1_h", "tab_yqs": "nav_1_1" });
    
    this.data.startDate = getDate(-7);
    this.data.endDate = getDate();
    this.data.pageCount = 10;
    this.data.index = 1;
    this.setData({ startDate: this.data.startDate, endDate: this.data.endDate });
    // getList(this);/
  },
  bindTimeChange: function (e) {
    this.setData({
      time: e.detail.value
    });
  },
  //  点击日期组件确定事件  
  bindDateChageStart: function (e) {
    this.setData({
      startDate: e.detail.value
    });
    this.data.startDate = e.detail.value;
    //原查询方法使用与公办
    //getList(this);

    getOrderList(this);
  },
  bindDateChangeEnd: function (e) {
    this.setData({
      endDate: e.detail.value
    })
    this.data.endDate = e.detail.value;
    //原查询方法使用与公办
    //getList(this);

    getOrderList(this);
  },

  //扫码
  toScanQRcode() {

    wx.scanCode({
      success: (res) => {
        console.log("扫码结果");
        console.log(res.result);

        if (res.result.indexOf(",") == -1) {
          // wx.showToast({
          //   title: "抱歉，该订单状态为未处理",
          //   icon: 'none',
          //   duration: 3000
          // })
          wx.showModal({
            title: '提示',
            content: '抱歉，该运单状态为未受理',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              }
            }
          })

          return false
        }

        var values = res.result.split(",");
        var tenantCode = values[0];
        var orderNumber = values[1];

        if (tenantCode == undefined || tenantCode == null || tenantCode == "" || tenantCode == "null") {
          //app.tip("金融代码不存在", "none");
          // wx.showToast({
          //   title: "金融代码不存在",
          //   icon: 'none',
          //   duration: 3000
          // })

          wx.showModal({
            title: '提示',
            content: '金融代码不存在',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              }
            }
          })
          return false
        } else {
          if (tenantCode == config.tenantCode) {
            wx.navigateTo({ url: "../freightTrack/freightTrackDetail?dh=" + orderNumber })
          } else {
            //app.tip("抱歉！无法找到该运单，请检查运单号。", "none");
            // wx.showToast({
            //   title: "抱歉, 当前小程序为【" +app.appName+"】，请核实运单！",
            //   icon: 'none',
            //   duration: 3000
            // })
            wx.showModal({
              title: '提示',
              content: "抱歉, 当前小程序为【" + app.appName + "】，请核实运单！",
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            })
            return false
          }
        }
      },
      fail: (res) => {
        console.log(res);
        // wx.showToast({
        //   title: res,
        //   icon: 'none',
        //   duration: 3000
        // })
        wx.showModal({
          title: '提示',
          content: res,
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            }
          }
        })
        return false
      }
    })
  },
  orderNumberInput: function (e) {
    this.setData({
      inputOrderNumberValue: e.detail.value
    })
  },
  //放大镜跳转货物跟踪页
  toFreightTrack: function (e) {
    var orderNumber = this.data.inputOrderNumberValue;
    if (orderNumber == undefined || orderNumber == "") {
      app.tip("运单号不可以为空，请输入运单号", 'none')
    } else {
      wx.navigateTo({ url: "../freightTrack/freightTrackDetail?dh=" + orderNumber })
    }
  },

  doNavigateToEdit: function (e) {
    var id = e.currentTarget.dataset.id;
    var array = this.data.wuliu;
    var order = array[id];
    if (this.data.index == 1) {
      wx.navigateTo({ url: "orderDetailEdit?order=" + JSON.stringify(order) })
    }else {
      wx.navigateTo({ url: "orderDetail?orderNumber=" + order.orderNumber})
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.loginUser == null || app.loginUser.id == null && app.loginUser.mobile == null) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return;
    }
    if (this.data.startDate == ""){
      this.data.startDate = getDate();
    }
    if (this.data.endDate == ""){
      this.data.endDate = getDate();
    }
    //原查询方法使用与公办
    //getList(this);

    getOrderList(this);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.data.pageCount = 10;
    //原查询方法使用与公办
    //getList(this);

    getOrderList(this);
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.data.pageCount = this.data.pageCount + 10;
    //原查询方法使用与公办
    //getList(this);

    getOrderList(this);
  }
  // ,

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
});
/**
 * 获取当前日期
 */
var getDate = function (num) {
  let tempDate = new Date();
  if (num != undefined && "" != num) {
    tempDate.setDate(tempDate.getDate() + num);//获取AddDayCount天后的日期 
  }
  let nowDate = new Date(Date.parse(tempDate));
  //年  
  let Y = nowDate.getFullYear();
  //月  
  let M = (nowDate.getMonth() + 1 < 10 ? '0' + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1);
  //日  
  let D = nowDate.getDate() < 10 ? '0' + nowDate.getDate() : nowDate.getDate();
  return Y + "-" + M + "-" + D;
};

/**
 * 查询数据（定制版）
 */
function getOrderList(_this) {
  findList(_this, function (msg) {
    console.info(msg);
    let result = msg.data.content;
    if (Object.prototype.toString.call(result) === "[object Array]" && result.length > 0) {
      _this.setData({ 
        companyName: app.companyInfo.name, 
        wuliu: msg.data.content, 
        startDate: _this.data.startDate, 
        endDate: _this.data.endDate, 
        index: _this.data.index, 
        showView: true 
      });
    } else {
      _this.setData({
        showView: false,
        message: "抱歉，没有找到相关数据！",
        imagePath: "../images/noData.png",
        index: _this.data.index
      });
    }
  })
}

/**
 * 查询数据
 */
function getList(_this) {
  findList(_this, function (msg) {
    console.log(msg.data.content);
    let result = msg.data.content;
    let arr = new Array();
    if (Object.prototype.toString.call(result) === "[object Array]" && result.length > 0) {
      for (let i = 0; i < result.length; i++) {
        let temp = { dh: result[i].id, receiver: result[i].receiver, unloadPlace: result[i].unloadPlace, companyName: result[i].tenantName, orderCreateTime: result[i].orderCreateTime};
        if (result[i].generateFlag == 0 || result[i].generateFlag == false) {
          temp.generateFlag = 'wqs';
        }
        if (result[i].generateFlag == 1 || result[i].generateFlag == true) {
          temp.generateFlag = 'yqs';
        }
        if (undefined != result[i].orderNumber && "null" != result[i].orderNumber && null != result[i].orderNumber){
          temp.orderNumber = result[i].orderNumber
        }else{
          temp.orderNumber = "";
        }
        
        arr.push(temp);
      }
      _this.setData({ companyName: app.companyInfo.name, wuliu: arr, startDate: _this.data.startDate, endDate: _this.data.endDate, index: _this.data.index, showView: true});
    }else{
      _this.setData({
        showView: false,
        message: "抱歉，没有找到相关数据！",
        imagePath: "../images/noData.png", 
        index: _this.data.index
      });
    }
  })
}

/**
 * 请求数据
 */
function findList(_this, callback) {
  if (_this.data.startDate > _this.data.endDate) {
    app.tip("开始时间不能晚于结束时间", "none");
    return false;
  }
  wx.showLoading({ mask: true, title: "加载中" });
  let par = { 
    startDate: _this.data.startDate, 
    endDate: _this.data.endDate, 
    userId: app.loginUser.id, 
    mobile: app.loginUser.mobile, 
    flag: 0, 
    currentPage: 1, 
    pageSize: _this.data.pageCount, 
    code: config.tenantCode
  };

  if (_this.data.index != 0) {
    par.generateFlag = _this.data.index == 1 ? 0 : 1;// 0: 未受理 ,  1 : 已受理
  }

  // console.log(par);
  wx.request({
    url: config.requestUrl + "order/getOrderList",
    method: "GET",
    header: {
      "Content-Type": "application/x-www-form-urlencoded"//;charset=utf-8
    },
    data: { "data": par },
    success: function (msg) {
      callback(msg);
      wx.hideLoading();
    },
    fail: function (msg) {
      // console.log(msg);
      _this.setData({
        showView: false,
        message: "抱歉，没有找到相关数据！",
        imagePath: "../images/noData.png",
        index: _this.data.index
      });
      wx.hideLoading();
    }
  });
}